package com.sunyard.manage.controller;

import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.bulletin.BulletinAddBO;
import com.sunyard.dal.bo.bulletin.BulletinDeleteBO;
import com.sunyard.dal.bo.bulletin.BulletinDetailBO;
import com.sunyard.dal.bo.bulletin.BulletinQueryBo;
import com.sunyard.dal.bo.bulletin.BulletinUpdateBO;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.dto.BulletinDTO;
import com.sunyard.dal.entity.Bulletin;
import com.sunyard.dal.mapper.BulletinMapper;
import com.sunyard.manage.service.BulletinService;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.Response.HeaderResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Slf4j
@Api(tags = "BulletinController", description = "公告管理控制器")
@RestController
@RequestMapping(value = "/bulletin")
public class BulletinController {

    @Autowired
    BulletinService bulletinService;

    @Autowired
    private OperatorLogService operatorLogService;

    @Autowired
    BulletinMapper bulletinMapper;

    @ApiOperation("获取公告列表")
    @PostMapping(value = "/getBulletin")
    public BaseResult<DataGrid<BulletinDTO>> getBulletinList(HttpServletRequest request, @RequestBody PaginationBO<BulletinQueryBo> queryBO) throws Exception {
        return bulletinService.getBulletinList(request, queryBO);
    }

    @ApiOperation("获取公告发布的机构")
    @PostMapping(value = "/getBulletinOrg")
    public BaseResult<DataGrid<String>> getOrgByBulletinId(HttpServletRequest request, @RequestBody BulletinQueryBo bulletinQueryBo) {
        return bulletinService.getOrgByBulletinId(request, bulletinQueryBo);
    }

    /**
     * @Description: 添加公告
     * @Author: chengy.wei
     * @Date: 2022/7/06 18:24
     */
    @PostMapping(value = "/addBulletin")
    @ResponseBody
    @ApiOperation("添加公告")
    public BaseResult addBulletin(HttpServletRequest request, @RequestBody BulletinAddBO bulletinAddBO) {
        try {
            return bulletinService.addBulletin(request, bulletinAddBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 删除公告
     * @Author: chengy.wei
     * @Date: 2022/7/06 18:24
     */
    @PostMapping(value = "/delBulletin")
    @ResponseBody
    @ApiOperation("删除公告")
    public BaseResult delBulletin(HttpServletRequest request, @RequestBody BulletinDeleteBO bulletinDeleteBO) {
        try {
            return bulletinService.delBulletin(request, bulletinDeleteBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 修改公告
     * @Author: chengy.wei
     * @Date: 2022/7/06 18:24
     */
    @PostMapping("updateBulletin")
    @ResponseBody
    @ApiOperation("修改公告")
    public BaseResult editBulletin(HttpServletRequest request, @RequestBody BulletinUpdateBO bulletinUpdateBO) {
        try {
            return bulletinService.edit(request, bulletinUpdateBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 公告详情
     * @Author: chengy.wei
     * @Date: 2022/7/07 17:50
     */
    @PostMapping("detailBulletin")
    @ResponseBody
    @ApiOperation("公告详情")
    public BaseResult<Bulletin> detailBulletin(HttpServletRequest request, @RequestBody BulletinDetailBO bulletinDetailBO) {
        return bulletinService.detail(request, bulletinDetailBO);
    }

    /**
     * @Description: 公告导出
     * @Author: jiy.fang
     * @Date: 2019/7/23 21:10
     */
    @ApiOperation("公告导出")
    @RequestMapping(value = "/export")
    @ResponseBody
    public void exportOperator(HttpServletResponse response, HttpServletRequest request, @RequestBody PaginationBO<BulletinQueryBo> queryBO) {
        try {String opId = TokenUtil.getOpId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            //定义日志信息
            String logName = "公告导出";
            String operationDesc = "用户" + opName + "进行公告导出";
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);

            BulletinQueryBo bulletinQueryBo = queryBO.getParams();
            //当前系统登陆人id
            bulletinQueryBo.setLoginOpId(opId);
            List<BulletinDTO> bulletinList = bulletinMapper.getBulletinList(bulletinQueryBo);
            if (bulletinList == null || bulletinList.isEmpty()) {
                throw new RuntimeException("无数据无需导出");
            }
            String title = "公告信息导出" + Math.random() + ".xls";
            String[] headers = new String[]{"公告ID", "标题名称", "公告内容", "发布时间", "是否已读", "发布人ID", "发布人用户名"};

            List<Object[]> dataList;
            String[] StatusArr = {"未读", "已读"};
            dataList = bulletinList.stream().map(bulletinDTO -> {
                Object[] obj = new Object[headers.length];
                obj[0] = bulletinDTO.getBulletinId();
                obj[1] = bulletinDTO.getTitleName();
                obj[2] = bulletinDTO.getContent();
                obj[3] = bulletinDTO.getCreateDatetime();
                obj[4] = StatusArr[Integer.parseInt(bulletinDTO.getHasRead())];
                obj[5] = bulletinDTO.getOpId();
                obj[6] = bulletinDTO.getOpName();
                return obj;
            }).collect(toList());

            OutputStream out = null;
            // 防止中文乱码
            String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput(title, headers, dataList);
            ex.export(out);
            log.info("公告信息导出");
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            HeaderResult.setFailHeader(request, response, e.getMessage());
        }
    }
}
